package com.wuxiaolong.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.wuxiaolong.wechat.common.BusinessException;
import com.wuxiaolong.wechat.common.JsonResult;
import com.wuxiaolong.wechat.common.ResultCode;
import com.wuxiaolong.wechat.service.MessageService;
import com.wuxiaolong.wechat.util.BeanXmlUtil;
import com.wuxiaolong.wechat.util.WxUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author Leo
 * @date 2019/8/5
 */
@RestController
@Getter
@Setter
@Slf4j
public class TestController {

    @Value("${wechat.token}")
    private String token;

    @Autowired
    private MessageService messageService;

    private HashMap<String,String> map = new HashMap<>();
    /**
     * 接收微信服务器发送过来的第一个GET请求
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wx", method = RequestMethod.GET)
    public String testGet(HttpServletRequest request, HttpServletResponse response){

        /**
         * 1.获得请求参数
         * 参数	描述
         * signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
         * timestamp	时间戳
         * nonce	随机数
         * echostr	随机字符串
         */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");


        // 2.开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
        if(WxUtil.checkSign(token, timestamp, nonce, signature)){
            // 3.若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
            log.info("配置成功");
            return echostr;
        }else {
            log.error("配置失败");
            return ResultCode.SIGN_ERR.getMsg();
        }


    }

    /**
     * 接收普通消息和事件推送 微信服务器在五秒内收不到响应会断掉连接，并且重新发起请求，总共重试三次
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wx", method = RequestMethod.POST)
    public String testPost(HttpServletRequest request, HttpServletResponse response) throws Exception{

        // 处理消息和事件推送
        Map<String,String> requestMap = BeanXmlUtil.xmlToMap(request.getInputStream());

        log.info("收到用户信息：{}",JSON.toJSONString(requestMap));

        // 重复消息不处理
        String msgId = requestMap.get("MsgId");
        String exit = map.get(msgId);
        if(! StringUtils.isEmpty(exit)){
            return "重复数据，不处理";
        }else {
            map.put(msgId,"aa");
        }

        // 获得响应消息xml
        String responseXmlStr = messageService.getResponseXmlStr(requestMap);

        log.info("响应用户信息：{}",responseXmlStr);

        return responseXmlStr;
    }
}
